import { useRef, useState } from 'react';


export default function (fetchData, { updatePageInfo, pagination }) {
    const tableState = useRef({ pagination });
    const [loading, setLoading] = useState(false);
    const handleChange = (pagination, filters, sorter, extra, search) => {      
        let _pagination = pagination || tableState.current.pagination;
        // * 关键字搜索的时候回到第一页
        if (extra?.action === 'search') {
            _pagination = {
                ..._pagination,
                current: 1
            }
        }
        let _sort = sorter || tableState.current.sorter;
        let _filters = filters || tableState.current.filters;
        let _search = search || tableState.current.search;
        //* 更新最新的pagination
        tableState.current.pagination = _pagination;
        //* 更新最新的sorter
        tableState.current.sorter = _sort;
        //* 更新最新的filters
        tableState.current.filters = _filters;
        //* 更新最新的search keyword
        tableState.current.search = _search;

        // * 触发数据重新获取
        if (typeof fetchData === 'function') {
            setLoading(true);
            fetchData(_filters, _pagination, formatSort(_sort), _search || {}, extra).then((data) => {
                updatePageInfo({
                    ..._pagination,
                    total: data?.total
                });
            }).finally(() => {
                setLoading(false);
            })
        } else {
            updatePageInfo({
                ..._pagination
            });
        }
    };

    const refreshTable = (params, extra) => {
        const pagination = params?.pagination;
        const filters = params?.filters;
        const sorter = params?.sorter;
        const search = params?.search;
        handleChange(pagination, filters, sorter, extra, search);
    }

    //后端要求排序传desc,asc
    const formatSort = (sorter) => {
        if (!sorter?.order) return {};
        return sorter.order === 'descend' ? { ...sorter, order: 'desc' } : { ...sorter, order: 'asc' };
    }
    return { handleChange, refreshTable, loading, tableState };
}